#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "log.hpp"

using namespace std;
const int size = 1024;

Log lg;

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " port[1024+]\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string severip = argv[1];
    uint16_t severport = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        lg(fatal, "socker error, errno : %d ", errno);
        exit(1);
    }
    lg(info, "sock success");

    struct sockaddr_in server;
    bzero(&server, sizeof(server)); 
    server.sin_family = AF_INET;
    server.sin_port = htons(severport);
    server.sin_addr.s_addr = inet_addr(severip.c_str());
    socklen_t len = sizeof(server);
 

    std::string message;
    while (true)
    {
        std::cout << "Please Enter$ ";
        //getline(cin, message);
        getline(cin, message);
        cout << message <<endl;
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, len);
        lg(info,"success sendto");

        struct sockaddr_in temp;
        socklen_t lent = sizeof(temp);
        char buffer[size];
        int s = recvfrom(sockfd,&buffer,sizeof(buffer)-1,0,(struct sockaddr*)&temp,&lent);
        if(s > 0)
        {
            buffer[size] = 0;
            cout << buffer <<endl;
        }

    }

    close(sockfd);
    return 0;
}